package com.kg.sdk.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.common.network.NetworkConfigData;
import com.common.network.NetworkResponse;
import com.common.network.RequestListener;
import com.kg.sdk.KPGameSdk;
import com.kg.sdk.SharedPreferencesCtrl;
import com.kg.sdk.dlg.KPDlgTip;
import com.kg.sdk.network.KPHeaderSetting;
import com.kg.sdk.network.KPPostRequest;
import com.kg.sdk.util.CommonUtil;
import com.kg.sdk.util.Helper;
import com.kg.sdk.util.KPNetworkData;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;

public class KPChargeActivity extends KPCommonActivity {
    String auth_code = "";
    String auth_key = "";
    private TextView tvUserName;
    private TextView tvMoney;
    private TextView tvCharge;
    private ImageView imgCode;
    private Bitmap lastBitmap;
    KPDlgTip mKPDlgTip;
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        int layoutId = Helper.getLayoutResId(this,"act_charge_layout");
        View view = LayoutInflater.from(this).inflate(layoutId, null);
        setContentView(view);
        SharedPreferencesCtrl sharedPreferencesCtrl = new SharedPreferencesCtrl(this, KPNetworkData.KPGAME);
        auth_code = sharedPreferencesCtrl.getString(KPNetworkData.AUTH_CODE_KYE, "");
        auth_key = sharedPreferencesCtrl.getString(KPNetworkData.AUTH_KYE, "");

        tvUserName = (TextView)findViewById(Helper.getIdResId(this,"tvUserName"));
        tvMoney = (TextView)findViewById(Helper.getIdResId(this,"tvMoney"));
        tvCharge = (TextView)findViewById(Helper.getIdResId(this,"tvCharge"));
        imgCode = (ImageView)findViewById(Helper.getIdResId(this,"imgCode"));
        TextView tvCopyWX = (TextView)findViewById(Helper.getIdResId(this,"tvCopyWX"));
        ImageView imgKf = (ImageView)findViewById(Helper.getIdResId(this,"imgKf"));
        imgKf.setVisibility(View.GONE);
        tvCharge.setVisibility(View.GONE);
        Intent intent = getIntent();
        if(intent != null){
            String account = intent.getStringExtra(KPNetworkData.ACCOUNT);
            String superls = intent.getStringExtra(KPNetworkData.SURPLUS);
            tvMoney.setText(superls);
            tvUserName.setText(account);
        }
        tvCopyWX.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtil.copy(KPChargeActivity.this,wx);
              //  CommonUtil.showToast(KPChargeActivity.this,"微信复制成功");
                mKPDlgTip.setTip("微信复制成功");
                mKPDlgTip.showDialog();
            }
        });
        getServer();
        KPGameSdk.hideFloatView1(this);
        mKPDlgTip  = new KPDlgTip(this);
    }

    private void charge(){


        RequestListener listener = new RequestListener() {
            @Override
            public void onSuccess(NetworkResponse result) {
                int code = result.getInt(KPNetworkData.ERROR_CODE);
                String data = result.getString(NetworkConfigData.DATA_KEY);
                Log.e("data"," usce center2 logni success is "+data);
                if(code == KPNetworkData.SUCCESS){

                }else{
                    final String errorMsg = result.getString(KPNetworkData.MSG_KEY);
                    showError(errorMsg);
                }
            }

            @Override
            public void onError(NetworkResponse error) {
                final String errorMsg = error.getString(NetworkConfigData.MESSAGE_KEY);
                showError(errorMsg);
                Log.e("data"," login errorMsg is "+errorMsg);
            }
        };
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("ordersn","2017071017283610159");
            jsonObject.put("pay_type","3");
            jsonObject.put("game_id","16");
            jsonObject.put("product","首充");
            jsonObject.put("role_id","1000");
            jsonObject.put("amount","6");
            jsonObject.put("server_id","server001");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(KPNetworkData.USER_CHARGE,jsonObject,listener);
    }
    private void request(String url,JSONObject jsonObject,RequestListener listener){
        mWaitingDialog.showDialog();
        KPPostRequest postRequest = new KPPostRequest(this,url,jsonObject.toString(),listener);
        postRequest.header("auth_code",auth_code);
        postRequest.header("auth_key",auth_key);
        postRequest.startAsync();
    }
    private void showError(final String error){

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWaitingDialog.closeDialog();
                CommonUtil.showToast(KPChargeActivity.this,error);
            }
        });
    }
     String wx = "";
    private void getServer(){

        String url = KPNetworkData.USER_CENTER;
        RequestListener listener = new RequestListener() {
            @Override
            public void onSuccess(NetworkResponse result) {
                int code = result.getInt(KPNetworkData.ERROR_CODE);
                String data = result.getString(NetworkConfigData.DATA_KEY);
                Log.e("data"," usce center2 logni success is "+data);
                if(code == KPNetworkData.SUCCESS){
                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        String url = jsonObject.getString("qr");
                        getPic(url);
                        wx = jsonObject.getString("wx");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }else{
                    final String errorMsg = result.getString(KPNetworkData.MSG_KEY);
                    showError(errorMsg);
                }
            }

            @Override
            public void onError(NetworkResponse error) {
                final String errorMsg = error.getString(NetworkConfigData.MESSAGE_KEY);
                Log.e("data"," login errorMsg is "+errorMsg);
                showError(errorMsg);
            }
        };
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put(KPNetworkData.ACT_KEY,"server");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request(KPNetworkData.USER_CENTER,jsonObject,listener);

    }
    /**
     * 点击获取图片
     */
    public void getPic(final String url){


        new Thread(){
            @Override
            public void run() {
                //获取okHttp对象get请求,

                try {
                    OkHttpClient client = new OkHttpClient();

                    //获取请求对象
                    Request request = new Request.Builder().url(url).addHeader("x_sid", KPHeaderSetting.x_sid).build();

                    //获取响应体
                    ResponseBody body = client.newCall(request).execute().body();

                    //获取流
                    InputStream in = body.byteStream();
                    //转化为bitmap
                    final Bitmap bitmap = BitmapFactory.decodeStream(in);
                    if(bitmap == null){
                        return;
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            imgCode.setImageBitmap(null);
                            if(lastBitmap !=null){
                                lastBitmap.recycle();
                                lastBitmap = null;
                            }
                            lastBitmap = bitmap;
                            imgCode.setImageBitmap(lastBitmap);
                            mWaitingDialog.closeDialog();
                        }
                    });
                    //使用Hanlder发送消
                } catch (IOException e) {
                    e.printStackTrace();
                    //失败
                }

            }
        }.start();
    }

    public void onDestroy(){
        KPGameSdk.showFloatView1(this);
        super.onDestroy();
        if(mKPDlgTip != null){
            mKPDlgTip.closeDialog();
        }
    }

}
